import 'package:fluent_ui/fluent_ui.dart';

import '../../api/auth_api.dart';
import '../../model/auth_model.dart';
import '../../model/setting_model.dart';
import '../../utils/loading_utils.dart';
import '../../utils/rsa.dart';
import '../app/app_view_model.dart';

///登录字段-枚举
enum LoginField {
  tenant('授权码', 0, FluentIcons.anchor_lock, 'test01'),
  account('账号', 0, FluentIcons.account_management, 'test'),
  passwd('密码', 6, FluentIcons.lock, '123456'),
  captcha('验证码', 4, FluentIcons.album, null);

  final String label;
  final int minLen;
  final IconData iconData;
  final String? val;

  const LoginField(this.label, this.minLen, this.iconData, this.val);

  //校验方法
  String? validHandler(final String? val) {
    if (val == null || val.isEmpty) {
      return '$label不能为空';
    }
    if (val.isNotEmpty && minLen > 0) {
      final len = val.length;
      if (len < minLen) {
        return '$label长度不能低于$minLen位';
      }
    }
    return null;
  }
}

///验证码数据
class _Captcha {
  final String? key, base64;

  _Captcha({this.key, this.base64});
}

///认证视频模型
class AuthViewModel extends ChangeNotifier {
  _Captcha? _captcha;
  final _fields = <LoginField, TextEditingController>{
    for (var field in LoginField.values)
      field: TextEditingController(text: field.val),
  };

  ///获取验证码
  String get b64Captcha => _captcha?.base64 ?? '';

  ///获取字段控制器
  TextEditingController? getController(LoginField field) => _fields[field];

  ///获取字段值
  String? getFieldValue(final LoginField field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  ///触发生成验证码
  void toggleCaptcha() async {
    final api = await authApi.captcha();
    if (api.isSuccessed) {
      _captcha = _Captcha(key: api.key, base64: api.base64);
      notifyListeners();
    }
  }

  ///触发登录处理
  void toggleLogin(AppViewModel model, VoidCallback onSuccess) async {
    try {
      loading.showLoading();
      //登录数据
      var encPasswd = '';
      final passwd = getFieldValue(LoginField.passwd) ?? '';
      if (passwd.isNotEmpty) {
        encPasswd = await rsa.encryption(passwd);
      }
      final req = AuthLoginReq(
        tenantCode: getFieldValue(LoginField.tenant) ?? '',
        account: getFieldValue(LoginField.account) ?? '',
        passwd: encPasswd,
        sn: '',
        key: _captcha?.key ?? '',
        code: getFieldValue(LoginField.captcha) ?? '',
      );
      final res = await authApi.login(req);
      if (res.isSuccessed) {
        final setting = SettingModel.fromAuthRes(res);
        final ok = await model.saveSettingModel(setting);
        debugPrint('saveSettingModel(setting: ${setting.toMap()})=> $ok');
        if (ok) {
          onSuccess();
        }
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
